/*
 * spring-security-form - spring-security-form
 * Copyright © 2022-Present Jinan Yuanchuang Network Technology Co., Ltd. (support@topiam.cn)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cn.topiam.employee.sample.form.configuration;

import java.util.List;

import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityCustomizer;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

import cn.topiam.employee.sample.form.FormAuthenticationFailureHandler;
import cn.topiam.employee.sample.form.FormAuthenticationSuccessHandler;

/**
 * SecurityConfiguration
 *
 * @author SanLi
 * Created by qinggang.zuo@gmail.com / 2689170096@qq.com on  2022/10/21 15:15
 */
@Configuration
public class FormSampleSecurityConfiguration {

    @Bean
    public SecurityFilterChain formSecurityFilterChain(HttpSecurity http) throws Exception {
        //静态资源
        http.authorizeHttpRequests(registry -> {
            registry
                .requestMatchers(new AntPathRequestMatcher("/css/**", HttpMethod.GET.toString()),
                    new AntPathRequestMatcher("/js/**", HttpMethod.GET.toString()),
                    new AntPathRequestMatcher("/images/**", HttpMethod.GET.toString()),
                    new AntPathRequestMatcher("/webjars/**", HttpMethod.GET.toString()),
                    new AntPathRequestMatcher("/favicon.ico", HttpMethod.GET.toString()),
                    new AntPathRequestMatcher("/actuator/health", HttpMethod.GET.toString()))
                .permitAll();
            registry.anyRequest().authenticated();
        });
        http.formLogin(configurer -> {
            configurer.successHandler(new FormAuthenticationSuccessHandler());
            configurer.failureHandler(new FormAuthenticationFailureHandler());
        });
        http.csrf(AbstractHttpConfigurer::disable);
        return http.build();
    }

    @Bean
    public UserDetailsService userDetailsService(PasswordEncoder passwordEncoder) {
        UserDetails user = new User("topiam", passwordEncoder.encode("topiam.cn"), List.of());
        InMemoryUserDetailsManager inMemoryUserDetailsManager = new InMemoryUserDetailsManager();
        inMemoryUserDetailsManager.createUser(user);
        return inMemoryUserDetailsManager;
    }

    /**
     * 配置密码加密
     *
     * @return {@link PasswordEncoder}
     */
    @Bean
    @ConditionalOnMissingBean(value = PasswordEncoder.class)
    public PasswordEncoder passwordEncoder() {
        return PasswordEncoderFactories.createDelegatingPasswordEncoder();
    }
}
